package com.suyang.syt.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.suyang.syt.auth.AuthClass;
import com.suyang.syt.auth.AuthMethod;
import com.suyang.syt.context.BeanFactoryContext;
import com.suyang.syt.model.Dictionary;
import com.suyang.syt.model.dto.AjaxObj;
import com.suyang.syt.service.interfaces.DictionaryService;
import com.suyang.syt.util.EmptyUtil;
import com.suyang.syt.util.StringUtil;

@Controller
@RequestMapping("/admin/dictionary")
@AuthClass(value = "login")
public class DictionaryController {

	@Autowired
	private DictionaryService dictionaryService;

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list() {
		return "dictionary/list";
	}

	@RequestMapping(value = "/listTreegrid", method = RequestMethod.POST)
	@AuthMethod
	@ResponseBody
	public List<Dictionary> listTreegrid(HttpServletRequest request, String id) {
		try {
			long mid = 0;
			if (EmptyUtil.isNotEmpty(id)) {
				mid = Long.parseLong(id);
			}
			return dictionaryService.listTreegrid(mid);
		} catch (Exception e) {
			return null;
		}
	}

	@RequestMapping(value = "/listDictionary", method = RequestMethod.POST)
	@ResponseBody
	@AuthMethod
	public List<Dictionary> listDictionary(HttpServletRequest request, String name) {
		try {
			return BeanFactoryContext.getDictionarys().get(name);
		} catch (Exception e) {
			return new ArrayList<Dictionary>();
		}
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	@AuthMethod
	public AjaxObj add(HttpServletRequest request, String name, String code, long pid, int orderIndex) {
		try {
			return dictionaryService.add(name, code, pid, orderIndex);
		} catch (Exception e) {
			return new AjaxObj(0, StringUtil.ERROR_MSG);
		}
	}

	@RequestMapping(value = "/deletes", method = RequestMethod.POST)
	@ResponseBody
	@AuthMethod
	public AjaxObj deletes(HttpServletRequest request, String ids) {
		try {
			return dictionaryService.deletes(ids);
		} catch (Exception e) {
			return new AjaxObj(0, StringUtil.ERROR_MSG);
		}
	}

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ResponseBody
	@AuthMethod
	public AjaxObj update(HttpServletRequest request, String name, String code, long id, int orderIndex) {
		try {
			return dictionaryService.update(id, name, code, orderIndex);
		} catch (Exception e) {
			return new AjaxObj(0, StringUtil.ERROR_MSG);
		}
	}

}
